package threads;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import sjtu.ChatClient.SystemConstants;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

public class SendAudioThread implements Runnable {
	private String ip;
	private int port;
	private AudioRecord audioRecord;
	private byte [] audioBuffer;
	private boolean isStopped = false;
	
	private synchronized boolean isStopped(){
		return this.isStopped;
	}
	
	public synchronized void stop(){
		isStopped = true;
		audioRecord.stop();
		audioRecord.release();
	}
	
	public SendAudioThread(String ip, int port){
		this.ip = ip;
		this.port = port;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		int audioBufferSize = AudioRecord.getMinBufferSize(SystemConstants.AUDIO_FREQUENCY, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
		audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SystemConstants.AUDIO_FREQUENCY, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
		audioBuffer = new byte [audioBufferSize];
		audioRecord.getState();
		audioRecord.startRecording();
		
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket();
		} catch (SocketException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		while(isStopped() == false){
			int result = audioRecord.read(audioBuffer, 0, audioBuffer.length);
			
			if(result != AudioRecord.ERROR_BAD_VALUE && result != AudioRecord.ERROR_INVALID_OPERATION){
				try {
					if(socket != null){
						DatagramPacket packet = new DatagramPacket(audioBuffer, audioBuffer.length, new InetSocketAddress(ip, port));
						socket.send(packet);
					}
				} catch (SocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		socket.close();
	}

}
